package com.example.demo.tool;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * @CLASSNAME CommonUtil
 * @USER wql
 * @DATE 2021/1/21 18:51
 */
public class CommonUtil {

    /**
     * 根据路径下载文件
     * @param path
     * @return
     * @throws IOException
     */
    public static ResponseEntity<InputStreamResource> DownloadFile(String path) throws IOException {
        FileSystemResource file = new FileSystemResource(path);
        if (!file.isFile()) {
            return ResponseEntity.badRequest().build();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", URLEncoder.encode(file.getFilename(),"utf-8")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
